package com.school.graduation.mine.view;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.school.graduation.R;
import com.school.graduation.common.base.BaseActivity;
import com.school.graduation.model.Student;
import com.school.graduation.release.GlideImageLoader;
import com.school.graduation.util.ToastUtil;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;

import java.io.File;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.OnClick;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;
import de.hdodenhof.circleimageview.CircleImageView;

public class ModifyMsgActivity extends BaseActivity {

    private static final String DEFAULT_HEAD = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1489594854191&di=be7cc6c149fd5b934d4c5439cad9cff2&imgtype=0&src=http%3A%2F%2Fimg1.skqkw.cn%3A888%2F2014%2F12%2F06%2F15%2Fqbmg00cqsst-131110.jpg";

    @Bind(R.id.toolBar_modify)
    Toolbar toolBarModify;
    @Bind(R.id.img_modify)
    CircleImageView imgModify;
    @Bind(R.id.head_modify)
    RelativeLayout headModify;
    @Bind(R.id.name_text_modify)
    TextView nameTextModify;
    @Bind(R.id.name_modify)
    RelativeLayout nameModify;
    @Bind(R.id.password_modify)
    RelativeLayout passwordModify;
    @Bind(R.id.logout_modify)
    RelativeLayout logoutModify;

    private SharedPreferences sp;
    private MaterialDialog dialog;
    private SharedPreferences.Editor editor;

    public static void jumpToModify(Context context, Bundle bundle) {
        Intent intent = new Intent(context, ModifyMsgActivity.class);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    @Override
    public int getContentView() {
        return R.layout.activity_modify_mine;
    }

    @Override
    public void initData() {
        //5901bae7207f160e15c07a64
        /*sp = getSharedPreferences("head", 1);
        editor = sp.edit();*/
        initTitle();
        initHead();
        initUserName();
    }

    private void initUserName() {
        nameTextModify.setText(BmobUser.getCurrentUser().getUsername());
    }

    private void initHead() {
        Glide.with(context).load(R.mipmap.head).into(imgModify);
    }

    private void initTitle() {
        toolBarModify.setTitle("修改个人信息");
        toolBarModify.setTitleTextColor(getResources().getColor(R.color.md_white_1000));
    }

    @OnClick({R.id.head_modify, R.id.name_modify, R.id.password_modify})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.head_modify:
                //头像
                ImagePicker imagePicker = ImagePicker.getInstance();
                imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
                imagePicker.setShowCamera(true);  //显示拍照按钮
                imagePicker.setCrop(true);        //允许裁剪（单选才有效）
                imagePicker.setSaveRectangle(true); //是否按矩形区域保存
                imagePicker.setSelectLimit(1);    //选中数量限制
                Intent intent = new Intent(ModifyMsgActivity.this, ImageGridActivity.class);
                startActivityForResult(intent, 100);
                break;
            case R.id.name_modify:
                showUpdateUserNameDialog();
                break;
            case R.id.password_modify:
                //密码
                showUpdateUserPasswordDialog();
                break;
        }
    }

    private void showUpdateUserPasswordDialog() {
        new MaterialDialog.Builder(context)
                .content("输入新的密码")
                .input("请输入新的密码", "", new MaterialDialog.InputCallback() {
                    @Override
                    public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                        showProgressDialog();
                        updateUserPassword(input);
                    }
                }).build().show();
    }

    private void updateUserPassword(CharSequence input) {
        BmobUser newUser = new BmobUser();
        newUser.setPassword(input.toString());
        BmobUser currentUser = BmobUser.getCurrentUser(Student.class);
        newUser.update(currentUser.getObjectId(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    ToastUtil.makeShortToast(context, "更新用户密码成功");
                    BmobUser.getCurrentUser(Student.class).update();
                    dismissProgressDialog();
                } else {
                    ToastUtil.makeShortToast(context, "更新用户密码失败:" + e.toString());
                    dismissProgressDialog();
                }
            }
        });
    }

    private void dismissProgressDialog() {
        dialog.dismiss();
    }

    private void showUpdateUserNameDialog() {
        new MaterialDialog.Builder(context)
                .content("输入新的用户名")
                .input("请输入新的用户名", nameTextModify.getText().toString(), new MaterialDialog.InputCallback() {
                    @Override
                    public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                        showProgressDialog();
                        updateUserName(input);
                    }
                }).build().show();
    }

    private void updateUserName(final CharSequence input) {
        BmobUser newUser = new BmobUser();
        newUser.setUsername(input.toString());
        BmobUser currentUser = BmobUser.getCurrentUser(Student.class);
        newUser.update(currentUser.getObjectId(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    ToastUtil.makeShortToast(context, "更新用户昵称成功");
                    setName(input.toString());
                    BmobUser.getCurrentUser(Student.class).update();
                    dismissProgressDialog();
                } else {
                    ToastUtil.makeShortToast(context, "更新用户昵称失败:" + e.toString());
                    dismissProgressDialog();
                }
            }
        });
    }

    private void setName(String name) {
        nameTextModify.setText(name);
    }

    private void showProgressDialog() {
        dialog = new MaterialDialog.Builder(context)
                .title("正在修改")
                .content("请稍候......")
                .progress(true, 0)
                .build();
        dialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 100) {
                showProgressDialog();
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                upLoadImg(images.get(0).path);
            } else {
                Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void upLoadImg(String path) {
        final BmobFile file = new BmobFile(new File(path));
        file.upload(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    String url = file.getFileUrl();
                    updateUserImgMsg(url);
                } else {
                    ToastUtil.makeShortToast(context, "头像上传失败:" + e.toString());
                    dismissProgressDialog();
                }
            }
        });
    }

    private void updateUserImgMsg(final String url) {
        Student newUser = new Student();
        newUser.setAvatarUrl(url);
        Student currentUser = BmobUser.getCurrentUser(Student.class);
        newUser.update(currentUser.getObjectId(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    ToastUtil.makeShortToast(context, "更新用户头像成功");
                    setHead(url);
                    makeImgCache(url);
                    BmobUser.getCurrentUser(Student.class).update();
                    dismissProgressDialog();
                } else {
                    ToastUtil.makeShortToast(context, "更新用户头像失败:" + e.toString());
                    dismissProgressDialog();
                }
            }
        });
    }

    private void makeImgCache(String url) {
        editor.putString("head_url", url);
        editor.apply();
    }

    private void setHead(String url) {
        Glide.with(context).load(url).into(imgModify);
    }

    @OnClick(R.id.logout_modify)
    public void onViewClicked() {
        BmobUser.getCurrentUser().logOut();
        ToastUtil.makeShortToast(context,"退出登录成功");
        finish();
    }
}
